<!DOCTYPE HTML>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html lang="en-US">
<head>
  <meta charset="UTF-8">
  <title></title>
    <link rel="stylesheet" href="../resources/rooms/bootstrap.css" />
    <link rel="stylesheet" href="../resources/rooms/fontAwesome/css/prettify.css">
	<link rel="stylesheet" href="../resources/rooms/fontAwesome/css/font-awesome.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
  <script src="../resources/rooms/bootstrap.js"></script>
 <script src="https://cdn.firebase.com/v0/firebase.js"></script>
  <script src="http://staging.tokbox.com/v0.91/js/TB.min.js"></script>
  <link rel="stylesheet" href="../resources/rooms/app.css" />
</head>
<body>

<script type="text/javascript">
  $(function(){
    $('#namePrompt input').focus()
    // set a limit of 4 videos per session
    var connection_limit=4
    var session_id, api_key=21313161, token, status, current_user,userName;
    var current_topic='${topic}'
    var chatBox=new Firebase('https://adviseme.firebaseio.com/rooms/topics/'+current_topic+'/chatBox')
    // reference object for all the topics
    var topics=new Firebase('https://adviseme.firebaseio.com/rooms/topics')
    // reference object for current topic
    var current_topic_ref=new Firebase('https://adviseme.firebaseio.com/rooms/topics/'+current_topic)
    // create a new waitlist table
    var waitlist_ref=new Firebase('https://adviseme.firebaseio.com/rooms/topics/'+current_topic+'/waitlist')
    var current_userId=-1;
    // add a count to current_topic table count simply keeps track of the numbers of users in the room
    var users_count=new Firebase('https://adviseme.firebaseio.com/rooms/topics/'+current_topic+'/count')
        newCount=users_count.push()
        newCount.set({id:''})
        newCount.onDisconnect().remove()
    // limit waitlist query to 1 to get the front of the waitlist
    var nextInLine=waitlist_ref.startAt().limit(1)
    var nextInLine_id=undefined;
    
    /* --------------------------*
     * Filebase Event Listeners
     *---------------------------*/
     
    // listens to changes in # of users in the room
    users_count.on('value',function(data){
      var count=0
      data.forEach(function(){count++;})
      current_topic_ref.child('totalUser').set(count)
      $('#totalUser span').html(count)
      current_topic_ref.child('totalUser').onDisconnect.set(count-1)
    })
    // listens to changes in waitlist
    waitlist_ref.on('value',function(data){
      var count=0
      var before_me=0;
      // count the wailist
      data.forEach(function(data){count++;})
      // get Id of the person in the front of the waitlist
      nextInLine.once('value',function(data){
        data.forEach(function(data){
          nextInLine_id=data.ref().name()
        })
      })
      // update the position of the person who is currently waitlisted
      updateWaitlist(data)
    })
    chatBox.on('value',function(data){
      $('#displayChat ul').html('')
      data.forEach(function(data){
        var msg=data.val()
        console.log(msg['msg']=="new user")
        var template
        if(msg['msg']=="new user"){
          template='<li><center>'+msg['name']+' has join the room</center></li>'
        }else{
          template='<li><p><h4>'+msg['name']+': </h4>'+msg['msg']+'</p></li>' 
        }
        $('#displayChat ul').append(template)
      })
      $('#displayChat').animate({
        scrollTop:$('#displayChat ul').height()
      })
    })

    // get topic data api_key and session_id etc
    topics.once('value',function(data){
      // current topic object
      topic=data.child(current_topic).val()
      session_id=topic['session_id']
      // Post request, to generate a tokbox token using the session_id
      $.post('getToken',{"session_id" : session_id},function(data){
        token=data
        // creating a new Tokbox Session
        var session=TB.initSession(session_id)
        // setup tokbox session event
        session.addEventListener('sessionConnected', sessionConnectedHandler);
        session.addEventListener('streamCreated', addNewStreamHandler)
        session.addEventListener("streamDestroyed", streamDestroyedHandler);
        // connects to the session, this will fire up the 'sessionConnected' event
        session.connect(api_key, token)
        
        
        
        /* --------------------------*
         * Jquery Events
         *---------------------------*/
        // put the user onto the waitlist
        $('#waitlist_me').live('click',function(){
          // add a new person onto the waitlist table
          current_user=waitlist_ref.push()
          // init the object with an arbitary name,firebase API requires that the new object 
          // to be non-empty, it will generate a unique id for current_user
          current_user.set({name:""})
          // set auto-removal when the user disconnect from the page 
          current_user.onDisconnect().remove()
          // .name() returns the unique id for the current_user
          current_userId=current_user.name()
          $('#waitlist_success').show()
          $('#waitlist_me').hide()
          waitlist_ref.once('value',function(data){
            updateWaitlist(data)
          })
          status="waiting"
        })
        
        $('#join_chat').live('click',function(){
          joinChat()
          $('#join_chat').hide()
        })
        
        $('#namePrompt input').keyup(function(e){
          checkName()
          if(e.keyCode==13 && $('#namePrompt input').val()){
            userName=$('#namePrompt input').val()
            var newMsg=chatBox.push()
            newMsg.set({name:userName,msg:"new user"})
            closePrompt()
          }
        })
        $('.submitName').live('click',function(){
          userName=$('#namePrompt input').val()
          var newMsg=chatBox.push()
          newMsg.set({name:userName,msg:"new user"})
          closePrompt()
        })
        $('#chatInput input').keyup(function(e){
          if(e.keyCode==13){
            var value=$('#chatInput input').val()
            if(value.trim()!=''){
              var newMsg=chatBox.push()
              newMsg.set({name:userName, msg:value})
            }
            $('#chatInput input').val('')
          }
        })
        $('#chatInput input').focus(function(){
          console.log()
          $('.icon-comments-alt').css('color','#82080A')
        })
        $('#chatInput input').focusout(function(){
          $('.icon-comments-alt').css('color','#8D8F8F')
        })
        
        /* --------------------------*
         * Tokbox event Handlers
         *---------------------------*/
        // when the current user is connected to the topic session
        function sessionConnectedHandler(event){    
          if(event.connections.length<=connection_limit)
            $('#join_chat').show()
          else
            $('#waitlist_me').show()
          subscribeToStreams(event.streams)
        }
        // when a new stream is added 
        function addNewStreamHandler(event){
          var stream=event.streams[0]
          if(stream.connection.connectionId==session.connection.connectionId) return;
          var size=countSessionStream()
          if(size<connection_limit){
            $('#waitlist_me').hide()
            if(status=="chatting")
               $('#join_chat').hide()
            else
              $('#join_chat').show()
          } 
          var div= document.createElement('div')
          div.setAttribute('id', 'stream'+stream.streamId)
          div.setAttribute('class', 'eachVideo')
          $('#streams').append(div)
          session.subscribe(stream,div.id,{width:250, height:180})
        }
        // interate through all the streams in the session and display each stream
        function subscribeToStreams(streams){
          for(var i=0; i<streams.length;i++){
            if(streams[i].connection.connectionId==session.connection.connectionId) return;
            var div= document.createElement('div')
            div.setAttribute('id', 'stream'+streams[i].streamId)
            div.setAttribute('class', 'eachVideo')
            $('#streams').append(div)
            session.subscribe(streams[i],div.id,{width:250, height:180})
          }
        } 
        // When a user disconnects from a session
        function streamDestroyedHandler(event){
          var stream=event.streams[0]
          var size=countSessionStream()
          if(size<connection_limit){
            $('#waitlist_me').hide()
            if(current_userId==nextInLine_id){
              // initiate chat for the next user in line
              joinChat()
              $('#join_chat').hide()
            }else{
              if(status=="chatting" || status=="waiting")
                $('#join_chat').hide()
              else
                $('#join_chat').show()
            }
          }
        }
        // count how many streams are in this session
        function countSessionStream(){
          var size=0
          for(key in session.streams){
            if(session.streams.hasOwnProperty(key)) size++
          }
          return size;
        }
        // start publishing current user's video
        function joinChat(){
           nextInLine_id=''
           status="chatting"
           var template='<div id="myPublisherDiv"></div>'
           $('#myStream').append(template)
           publisher = TB.initPublisher(api_key,'myPublisherDiv',{width:250, height:180})
           session.publish(publisher)
           var c_u= new Firebase('https://adviseme.firebaseio.com/rooms/topics/'
                    +current_topic+'/waitlist/'+current_userId)
           c_u.remove()
           $('#waitlist_success').hide()
        }
        function checkName(){
          var value=$('#namePrompt input').val().trim()
          if(!value)
             $('.submitName').attr('disabled','disabled')
          else
            $('.submitName').removeAttr('disabled')
        }
        function closePrompt(){
          $('.background_dimmer').hide()
          $('.floatingContent').hide()
        }
        // if a person is waitlisted update the user's position in the waitlist
        
      }) // <-- end of post '/getToken'-->
    })// <-- end of topics.once -->
    function updateWaitlist(data){
      var before_me=1;
      for(key in data.exportVal()){
        if(key==current_userId){
          $('#waitlist_success span').html(before_me)
          return
        }
        before_me++
      }
    }
  }) // <-- end of document.ready -->
</script>
  <div id="main" class="container">
    <div id="main_left">
        <div class="topic_header">${topic}</div>
        <a href="../room" class="back_button">
          <i class="icon-circle-arrow-left"></i>
        </a> 
        <div id="streams">
         <div id="myStream"></div>
        </div>
        <div id="waitlist_success">You have been waitlisted! Position <span>1</span> </div>
        <div id="topic_control_container">
          <i id="totalUser" class="icon-group"><span>1</span></i>
          <div id="waitlist_me" class="topic_control">Waitlist Me</div>
          <div id="join_chat" class="topic_control">Join Chat</div>
        </div>
    </div>
    <div id="main_right">
      <div id="chatroom">
        <div id="displayChat"><ul></ul></div>
        <div id="chatInput">
          <input type="" />
          <i class="icon-comments-alt"></i>
        </div>
      </div>
    </div>
  </div>
  <div class="background_dimmer"></div>
  <div class="floatingContent">
    <div id="namePrompt">
      <h3>What's your name? </h3>
       <input type="" />
      <button class="submitName btn" disabled="disabled">Lets Chat!</button>
    </div>
  </div>
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-41970141-1', 'meetexpert.in');
  ga('send', 'pageview');

</script>
</body>
</html>